import { _decorator, Component, Node} from 'cc';
import { PageCore } from './PageCore';
import { ControllerBase } from '../Controller/ControllerBase';
import { NodeExtension } from '../../CCExtension/NodeExtension';
const { ccclass, property } = _decorator;


export class PageControllers extends PageCore {
    private controllers: Map<string, ControllerBase> = new Map();

    public init(data: {}): void {
        NodeExtension.visitAllDescendants(this.node,(descendant:Node)=>{
            let controller= descendant.getComponent(ControllerBase)

            if(controller)
            {
                controller.init(this)
                this.controllers.set(controller.getID(),controller)
            }
        })
    }

    public getController(id: string): ControllerBase | null {
        const controller = this.controllers.get(id);
        if (controller == null) {
            this.logErrorByID('获取控制器', id);
            return null;
        }
        return controller;
    }

    public ActiveController(id: string): void {
        const controller = this.controllers.get(id);
        if (controller == null) {
            this.logErrorByID('激活控制器', id);
            return;
        }
        controller.active();
    }

    public CloseAllController(): void {
        this.controllers.forEach((controller) => {
            controller.close();
        });
    }

    private logErrorByID(behavior: string, id: string): void {
        console.error(behavior + "时，指定ID的Controller不存在于UIPage中! PageID为:" + this.getID() + " Controller的ID为:" + id);
    }
}

